package com.huntmobi.springsecuritydemo.base.util;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * @Author：zouzhimin
 * @description：
 * @date：crealed in 16:15 2020/7/7
 * </P>
 **/
@Configuration
public class JwtUtil {

    @Value("${token.expirationSeconds}")
    private int expirationSeconds;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public String getToken(Collection<? extends GrantedAuthority> authorities, String userName) {

        StringBuffer stringBuffer = new StringBuffer();
        for (GrantedAuthority authority : authorities) {
            stringBuffer.append(authority.getAuthority());
        }

        //开始生成token
        String token = Jwts.builder()
                .claim("authorities", stringBuffer)
                .setSubject(userName)
                .setExpiration(new Date(System.currentTimeMillis() + expirationSeconds * 1000))
                .signWith(SignatureAlgorithm.HS512, "sang@123")
                .compact();

        // 一个token对应一个角色
        redisTemplate.opsForValue().set(token,stringBuffer.toString(), expirationSeconds * 1000, TimeUnit.SECONDS);

        return token;
    }

}
